import Foundation

class ImageUploadService {
    static let shared = ImageUploadService()
    private init() {}

    private let apiKey = "<ENTER IMGBB API KEY HERE>"

    func uploadImage(data: Data) async throws -> String {
        let url = URL(string: "https://api.imgbb.com/1/upload?key=\(apiKey)")!

        var request = URLRequest(url: url)
        request.httpMethod = "POST"

        let base64 = data.base64EncodedString()
        let encoded = base64.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? base64
        let body = "image=\(encoded)"

        request.httpBody = body.data(using: .utf8)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

        let (responseData, _) = try await URLSession.shared.data(for: request)
        print("ImgBB RAW RESPONSE:")
        print(String(data: responseData, encoding: .utf8) ?? "UNDECODEABLE")

        if let decoded = try? JSONDecoder().decode(ImgBBResponse.self, from: responseData) {
            return decoded.data.url
        }

        return String(data: responseData, encoding: .utf8) ?? "<<unknown>>"


    }
}

struct ImgBBResponse: Codable {
    struct ImgData: Codable {
        let url: String
    }
    let data: ImgData
}
